﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using DevExpress.XtraGrid;
using THSLib;
using THSERP.BusinessEntities;
namespace THSERP.BaseProvider
{
    public partial class THSSearchResultsGridControl : DevExpress.XtraGrid.GridControl, ICloneable
    {
        #region Variables
        protected THSERPScreen _screen;
        protected String _THSDataSource;
        protected String _THSFieldGroup;
        protected String _THSComment;
        protected String _THSError;
        protected String _THSPrivilege;
        protected  String _THSSelectType;
        protected  String _THSSelectTypeValue;
        #endregion

        #region Public Properties
        public THSERPScreen Screen
        {
            get
            {
                return _screen;
            }
            set
            {
                _screen = value;
            }
        }

        [Category("THS")]
        public String THSDataSource
        {
            get
            {
                return _THSDataSource;
            }
            set
            {
                _THSDataSource = value;
            }
        }

        [Category("THS")]
        public String THSFieldGroup
        {
            get
            {
                return _THSFieldGroup;
            }
            set
            {
                _THSFieldGroup = value;
            }
        }

        [Category("THS")]
        public String THSComment
        {
            get
            {
                return _THSComment;
            }
            set
            {
                _THSComment = value;
            }
        }

        [Category("THS")]
        public String THSError
        {
            get
            {
                return _THSError;
            }
            set
            {
                _THSError = value;
            }
        }

        [Category("THS")]
        public String THSPrivilege
        {
            get
            {
                return _THSPrivilege;
            }
            set
            {
                _THSPrivilege = value;
            }
        }
        [Category("THS")]
        public  String THSSelectType
        {
            get
            {
                return _THSSelectType;
            }
            set
            {
                _THSSelectType = value;
            }
        }

        [Category("THS")]
        public String THSSelectTypeValue
        {
            get
            {
                return _THSSelectTypeValue;
            }
            set
            {
                _THSSelectTypeValue = value;
            }
        }
        #endregion

        #region Constructors
        public THSSearchResultsGridControl()
        {
            InitializeComponent();
        }

        public THSSearchResultsGridControl(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
        #endregion

        #region Function Init Search Result GridControl
        public void InitializeControl()
        {
            DevExpress.XtraGrid.Views.Grid.GridView dgvSearchResults = InitializeSearchResultsGridView();
            this.ViewCollection.Add(dgvSearchResults);
            this.MainView = dgvSearchResults;
            dgvSearchResults.GridControl = this;
            this.MouseDoubleClick += new MouseEventHandler(GridControlSearchResults_MouseDoubleClick);

           
            this.UseEmbeddedNavigator = true;
            this.EmbeddedNavigator.Name = "navigator_" + this.Name;
            this.EmbeddedNavigator.Buttons.CustomButtons.AddRange(new DevExpress.XtraEditors.NavigatorCustomButton[] { new DevExpress.XtraEditors.NavigatorCustomButton(8, "Customize"), new DevExpress.XtraEditors.NavigatorCustomButton(9, "Save Customization") });
            this.EmbeddedNavigator.Buttons.Remove.Visible = false;
            this.EmbeddedNavigator.Buttons.Edit.Visible = false;
            this.EmbeddedNavigator.Buttons.Append.Visible = false;
            
            
            this.EmbeddedNavigator.ButtonClick += new DevExpress.XtraEditors.NavigatorButtonClickEventHandler(NavigatorButton_Click);

            
        }

        private DevExpress.XtraGrid.Views.Grid.GridView InitializeSearchResultsGridView()
        {
            DevExpress.XtraGrid.Views.Grid.GridView dgvSearchResults = new DevExpress.XtraGrid.Views.Grid.GridView();
            dgvSearchResults.Name = "fld_dgv" + this.Name.Substring(7);
            dgvSearchResults.OptionsSelection.EnableAppearanceFocusedCell = false;
            dgvSearchResults.OptionsSelection.EnableAppearanceFocusedRow = true;
            dgvSearchResults.OptionsView.ColumnAutoWidth = false;
            //dgvSearchResults.OptionsSelection.MultiSelect = true;
            dgvSearchResults.OptionsCustomization.AllowFilter = true;
            dgvSearchResults.OptionsView.ShowAutoFilterRow = true;
            dgvSearchResults.OptionsView.ShowFooter = true;
            //disable ShowGroupPanel_HieuNH_02/04/2010
            dgvSearchResults.OptionsView.ShowGroupPanel = false;
            dgvSearchResults.OptionsView.ShowIndicator = false;
            //dgvSearchResults.PaintStyleName = "Office2003";

            dgvSearchResults.Click += new EventHandler(GridViewSearchResults_OnClick);
            dgvSearchResults.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(GridViewSearchResults_FocusedRowChanged);
            dgvSearchResults.KeyUp += new KeyEventHandler(GridViewSearchResults_KeyUp);
            dgvSearchResults.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(GridViewSearchResults_CustomDrawCell);
            dgvSearchResults.OptionsBehavior.Editable = false;
            AddColumnsToGridViewResults(dgvSearchResults, this.Name.Substring(7) + 's');

            return dgvSearchResults;
        }

        private void AddColumnsToGridViewResults(DevExpress.XtraGrid.Views.Grid.GridView GridViewResults, String strTableName)
        {
            
            GridViewResults.Columns.Clear();
           
            AAColumnAliasController objAAColumnAliasController = new AAColumnAliasController();
            DataSet dsColumns = objAAColumnAliasController.GetAAColumnAliasByTableName(strTableName);
            if (dsColumns.Tables[0].Rows.Count > 0)
            {

                foreach (DataRow rowColumn in dsColumns.Tables[0].Rows)
                {
                    AAColumnAliasInfo objAAColumnAliasInfo = (AAColumnAliasInfo)objAAColumnAliasController.GetObjectFromDataRow(rowColumn);
                    if (objAAColumnAliasInfo != null)
                    {
                        DevExpress.XtraGrid.Columns.GridColumn col = new DevExpress.XtraGrid.Columns.GridColumn();
                        col.Name = "col" + objAAColumnAliasInfo.AAColumnAliasName;
                        col.FieldName = objAAColumnAliasInfo.AAColumnAliasName;
                        col.Caption = objAAColumnAliasInfo.AAColumnAliasCaption;
                        col.Width = 100;
                        col.VisibleIndex = -1;

                        if (THSDbUtil.IsForeignKey(strTableName, objAAColumnAliasInfo.AAColumnAliasName))
                        {
                            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupEdit = InitColumnLookupEdit(strTableName, objAAColumnAliasInfo.AAColumnAliasName);
                            if (repLookupEdit != null)
                                col.ColumnEdit = repLookupEdit;
                        }
                        else
                        {
                            String strConfigValueTable = String.Empty;
                            if (objAAColumnAliasInfo.AAColumnAliasName.EndsWith("Combo"))
                                strConfigValueTable = objAAColumnAliasInfo.AAColumnAliasName.Substring(2, objAAColumnAliasInfo.AAColumnAliasName.Length - 7);
                            else
                                strConfigValueTable = objAAColumnAliasInfo.AAColumnAliasName.Substring(2, objAAColumnAliasInfo.AAColumnAliasName.Length - 2);
                           //hieu.nguyen modified 16/08/2011 add dummy fiedl fo combo reponsitory
                            //binding datasource 
                            if (ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueTable] != null)
                            {
                                DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupEdit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
                                repLookupEdit.ValueMember = "Value";
                                repLookupEdit.DisplayMember = "Text";
                                DataTable dtSource = ADConfigValueUtility.glbdsConfigValues.Tables[strConfigValueTable];
                                    if (dtSource.Rows.Count > 0)
                                    {
                                        if (!String.IsNullOrEmpty(dtSource.Rows[0][repLookupEdit.ValueMember].ToString()))
                                        {
                                            
                                            DataRow row = dtSource.NewRow();
                                            row[repLookupEdit.DisplayMember] =String.Empty;
                                            row[repLookupEdit.ValueMember] = String.Empty;
                                            row["Key"] = "DummyField";
                                            dtSource.Rows.InsertAt(row, 0);
                                        }
                                    }
                                repLookupEdit.DataSource = dtSource;
                                DevExpress.XtraEditors.Controls.LookUpColumnInfo repColumn = new DevExpress.XtraEditors.Controls.LookUpColumnInfo();
                                repColumn.FieldName = "Text";
                                repColumn.Caption = "";
                                repColumn.Width = 100;
                                repLookupEdit.Columns.Add(repColumn);
                                repLookupEdit.PopupWidth = repColumn.Width;
                                col.ColumnEdit = repLookupEdit;
                            }
                            else
                            {
                                
                                col.ColumnEdit = InitColumnRepositoryFromFieldFormatGroup(strTableName, objAAColumnAliasInfo.AAColumnAliasName);
                            }
                        }

                        if (col.FieldName.Contains("MatchCode"))
                        {
                            String strKey = col.FieldName.Substring(2, col.FieldName.Length - 2);
                            if (col.FieldName.EndsWith("Combo"))
                                strKey = strKey.Substring(0, strKey.Length - 5);

                            String strCaption = ADConfigValueUtility.GetTextFromKey(strKey);
                            if (!String.IsNullOrEmpty(strCaption))
                                col.Caption = strCaption;
                        }

                        
                        if (col.ColumnEdit != null)
                            InitColumnRepositoryFormat(col, strTableName, objAAColumnAliasInfo.AAColumnAliasName);
                        else
                            InitColumnFormat(col, strTableName, objAAColumnAliasInfo.AAColumnAliasName);

                        GridViewResults.Columns.Add(col);
                    }
                }
            }
            else
            {
                //Column Primary 
                String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strTableName);

                DevExpress.XtraGrid.Columns.GridColumn colPrimaryColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                colPrimaryColumn.Name = "col" + strPrimaryColumn;
                colPrimaryColumn.FieldName = strPrimaryColumn;
                colPrimaryColumn.Caption = "ID";
                colPrimaryColumn.VisibleIndex = -1;
                GridViewResults.Columns.Add(colPrimaryColumn);

                //Column Name
                DevExpress.XtraGrid.Columns.GridColumn colNo = new DevExpress.XtraGrid.Columns.GridColumn();
                colNo.Name = "col" + strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No";
                colNo.FieldName = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No";
                colNo.Caption = "No";
                colNo.VisibleIndex = -1;
                GridViewResults.Columns.Add(colNo);

                //Column Name
                DevExpress.XtraGrid.Columns.GridColumn colName = new DevExpress.XtraGrid.Columns.GridColumn();
                colName.Name = "col" + strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Name";
                colName.FieldName = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Name";
                colName.Caption = "Name";
                colName.VisibleIndex = -1;
                GridViewResults.Columns.Add(colName);

                //Column Desc
                DevExpress.XtraGrid.Columns.GridColumn colDesc = new DevExpress.XtraGrid.Columns.GridColumn();
                colDesc.Name = "col" + strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Desc";
                colDesc.FieldName = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Desc";
                colDesc.Caption = "Description";
                colDesc.VisibleIndex = -1;
                GridViewResults.Columns.Add(colDesc);

            }
            InitGridViewResult(GridViewResults, Screen.Module.Name, strTableName);
        }

        
        public DevExpress.XtraEditors.Repository.RepositoryItem InitColumnRepositoryFromFieldFormatGroup(String strTableName, String strColumnName)
        {
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            STFieldFormatGroupsInfo objFieldFormatGroupsInfo = objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Screen.Module.Name, strTableName, strColumnName);
            if (objFieldFormatGroupsInfo != null)
            {
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupRepository))
                {
                    return THSUtil.GetRepositoryItemFromText(objFieldFormatGroupsInfo.STFieldFormatGroupRepository);
                }
            }
            return null;
        }

        
        public void InitColumnRepositoryFormat(DevExpress.XtraGrid.Columns.GridColumn column, String strTableName, String strColumnName)
        {
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            STFieldFormatGroupsInfo objFieldFormatGroupsInfo = objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Screen.Module.Name, strTableName, strColumnName);
            if (objFieldFormatGroupsInfo != null)
            {
                DevExpress.XtraEditors.Repository.RepositoryItem rep = column.ColumnEdit;
                if (objFieldFormatGroupsInfo.STFieldFormatGroupBackColor > 0)
                {
                    rep.Appearance.BackColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupBackColor);
                    rep.Appearance.Options.UseBackColor = true;
                }
                if (objFieldFormatGroupsInfo.STFieldFormatGroupForeColor > 0)
                {
                    rep.Appearance.ForeColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupForeColor);
                    rep.Appearance.Options.UseForeColor = true;
                }

                String strDefaultFontName = "Tahoma";
                float fDefaultFontSize = 8.25F;
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFontName))
                    strDefaultFontName = objFieldFormatGroupsInfo.STFieldFormatGroupFontName;
                if (objFieldFormatGroupsInfo.STFieldFormatGroupFontSize > 0)
                    fDefaultFontSize = objFieldFormatGroupsInfo.STFieldFormatGroupFontSize;
                rep.Appearance.Font = new Font(strDefaultFontName, fDefaultFontSize);
                rep.Appearance.Options.UseFont = true;

                if (THSUtil.IsEditRepository(rep))
                {
                    DevExpress.XtraEditors.Repository.RepositoryItemTextEdit repText = (DevExpress.XtraEditors.Repository.RepositoryItemTextEdit)rep;
                    if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                    {
                        repText.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                        repText.Mask.EditMask = String.Format("n{0}", objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound);
                        repText.Mask.UseMaskAsDisplayFormat = true;
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType))
                        {
                            repText.Mask.MaskType = THSUtil.GetMaskTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupMaskType);
                            repText.Mask.EditMask = objFieldFormatGroupsInfo.STFieldFormatGroupMaskEdit;
                            repText.Mask.UseMaskAsDisplayFormat = true;
                        }
                        if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                        {
                            repText.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                            repText.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                        }
                    }
                }
            }
        }

        
        public void InitColumnFormat(DevExpress.XtraGrid.Columns.GridColumn column, String strTableName, String strColumnName)
        {
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            STFieldFormatGroupsInfo objFieldFormatGroupsInfo = objFieldFormatGroupsController.GetFieldFormatGroupByModuleNameAndTableNameAndColumnName(this.Screen.Module.Name, strTableName, strColumnName);
            if (objFieldFormatGroupsInfo != null)
            {
                if (objFieldFormatGroupsInfo.STFieldFormatGroupBackColor > 0)
                {
                    column.AppearanceCell.BackColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupBackColor);
                    column.AppearanceCell.Options.UseBackColor = true;
                }
                if (objFieldFormatGroupsInfo.STFieldFormatGroupForeColor > 0)
                {
                    column.AppearanceCell.ForeColor = Color.FromArgb(objFieldFormatGroupsInfo.STFieldFormatGroupForeColor);
                    column.AppearanceCell.Options.UseForeColor = true;
                }

                String strDefaultFontName = "Tahoma";
                float fDefaultFontSize = 8.25F;
                if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFontName))
                    strDefaultFontName = objFieldFormatGroupsInfo.STFieldFormatGroupFontName;
                if (objFieldFormatGroupsInfo.STFieldFormatGroupFontSize > 0)
                    fDefaultFontSize = objFieldFormatGroupsInfo.STFieldFormatGroupFontSize;
                column.AppearanceCell.Font = new Font(strDefaultFontName, fDefaultFontSize);
                column.AppearanceCell.Options.UseFont = true;

                if (objFieldFormatGroupsInfo.STFieldFormatGroupDecimalRound > 0)
                {
                    column.ColumnEdit = THSUtil.GetRepositoryItemFromText("RepositoryItemTextEdit");
                    InitColumnRepositoryFormat(column, strTableName, strColumnName);
                }
                else
                {
                    if (!String.IsNullOrEmpty(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType))
                    {
                        column.DisplayFormat.FormatType = THSUtil.GetFormatTypeFromText(objFieldFormatGroupsInfo.STFieldFormatGroupFormatType);
                        column.DisplayFormat.FormatString = objFieldFormatGroupsInfo.STFieldFormatGroupFormatString;
                    }
                }
            }
        }

        protected virtual DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit InitColumnLookupEdit(String strTableName, String strColumnName)
        {
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit rep = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            rep.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            rep.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoFilter;
            rep.NullText = String.Empty;

            
            String strLookupTable = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(strTableName, strColumnName);
            if (THSApp.LookupTables[strLookupTable] == null)
                return null;
            String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strLookupTable);
            String strDisplayColumn = GetLookupTableDisplayColumn(strLookupTable);
            rep.ValueMember = strPrimaryColumn;
            rep.DisplayMember = strDisplayColumn;
            DataSet ds = (DataSet)THSApp.LookupTables[strLookupTable];
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToInt32(ds.Tables[0].Rows[0][rep.ValueMember]) > 0)
                    {
                        DataRow row = ds.Tables[0].NewRow();

                        row[rep.DisplayMember] = String.Empty;
                        row[rep.ValueMember] = 0;
                        ds.Tables[0].Rows.InsertAt(row, 0);
                    }
                }
            }
            
            rep.DataSource = ds.Tables[0];
            rep.QueryPopUp += new CancelEventHandler(RepositoryItemLookupEdit_QueryPopup);
            DevExpress.XtraEditors.Controls.LookUpColumnInfo colName = new DevExpress.XtraEditors.Controls.LookUpColumnInfo();
            colName.FieldName = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No";
            colName.Caption = "No";
            colName.Width = 100;

            rep.Columns.Add(colName);

            return rep;
        }

        protected virtual String GetLookupTableDisplayColumn(String strLookupTableName)
        {
           
            String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strLookupTableName);
            String prefix = strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2);
            if (THSDbUtil.ColumnIsExist(strLookupTableName, prefix + "Name"))
                return prefix + "Name";
            else if (THSDbUtil.ColumnIsExist(strLookupTableName, prefix + "No"))
                return prefix + "No";
            return String.Empty;
        }

        protected virtual void RepositoryItemLookupEdit_QueryPopup(object sender, CancelEventArgs e)
        {
           
            DevExpress.XtraEditors.LookUpEdit lke = (DevExpress.XtraEditors.LookUpEdit)sender;
            String strLookupTable = lke.Properties.ValueMember.Substring(0, lke.Properties.ValueMember.Length - 2) + "s";
            DateTime dtLastCreatedDate = THSDbUtil.GetLastCreatedDateOfTable(strLookupTable);

            if (dtLastCreatedDate.CompareTo(((DateTime)THSApp.LookupTablesUpdatedDate[strLookupTable])) > 0)
            {
                //Refesh Data Source
                BaseBusinessController objLookupTableController = BusinessControllerFactory.GetBusinessController(strLookupTable + "Controller");
                if (objLookupTableController != null)
                {
                    DataSet ds = objLookupTableController.GetAllObjects();

                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            if (Convert.ToInt32(ds.Tables[0].Rows[0][lke.Properties.ValueMember]) > 0)
                            {
                                DataRow row = ds.Tables[0].NewRow();

                                row[lke.Properties.DisplayMember] = String.Empty;
                                row[lke.Properties.ValueMember] = 0;
                                ds.Tables[0].Rows.InsertAt(row, 0);
                            }
                        }
                        BindingSource bds = new BindingSource();
                        bds.DataSource = ds.Tables[0];
                        lke.Properties.DataSource = bds;
                        bds.ResetBindings(false);

                        // Update Last Updated Date of Lookup Table
                        THSApp.LookupTablesUpdatedDate[strLookupTable] = DateTime.Now;
                        ((DataSet)THSApp.LookupTables[strLookupTable]).Tables.Clear();
                        ((DataSet)THSApp.LookupTables[strLookupTable]).Tables.Add(ds.Tables[0].Copy());
                    }
                }
            }
        }

        public virtual void GridViewSearchResults_OnClick(object sender,EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView dgvSearchResults = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            int rowHandle = dgvSearchResults.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                String strMainTable = ((BaseModuleERP)Screen.Module).CurrentModuleEntity.MainObject.GetType().Name.Substring(0, ((BaseModuleERP)Screen.Module).CurrentModuleEntity.MainObject.GetType().Name.Length - 4);
                DataRow row = dgvSearchResults.GetDataRow(rowHandle);
                if (row != null)
                {
                    Screen.Module.Toolbar.CurrentIndex = Screen.Module.Toolbar.ObjectCollection.Tables[0].Rows.IndexOf(row);
                    Screen.Module.Toolbar.Invalidate();
                }
            }
        }
       
        private void GridViewSearchResults_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView dgvSearchResults = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            String strMainTable = ((BaseModuleERP)Screen.Module).CurrentModuleEntity.MainObject.GetType().Name.Substring(0, ((BaseModuleERP)Screen.Module).CurrentModuleEntity.MainObject.GetType().Name.Length - 4);
            DataRow row = dgvSearchResults.GetDataRow(dgvSearchResults.FocusedRowHandle);
            if (row != null)
            {
                Screen.Module.Toolbar.CurrentIndex = Screen.Module.Toolbar.ObjectCollection.Tables[0].Rows.IndexOf(row);                
                Screen.Module.Toolbar.Invalidate();
            }
        }

        private void GridViewSearchResults_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DevExpress.XtraGrid.Views.Grid.GridView gridView = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                int iObjectID = ((BaseModuleERP)Screen.Module).Toolbar.CurrentObjectID;
                //change delete object by ActionDelete. purpose to check object if this object can not delete by condition_HieuNH_02/04/2010
                //((BaseModuleERP)Screen.Module).Delete(iObjectID);
                ((BaseModuleERP)Screen.Module).ActionDelete();
                ((BaseModuleERP)Screen.Module).Search();
                ((BaseModuleERP)Screen.Module).InvalidateAfterSearch(null, String.Empty);
            }
            if (e.KeyCode == Keys.Escape || e.KeyCode == Keys.Enter)
            {
                ((BaseModuleERP)Screen.Module).ActivateDataMainScreen();
            }
        }

        private void GridViewSearchResults_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column.VisibleIndex >= 0)
            {
                try
                {
                    String strTableName = THSUtil.GetTableNameFromBusinessObject(((BaseModuleERP)Screen.Module).CurrentModuleEntity.MainObject);
                    String strColumnName = e.Column.FieldName;
                   
                    if (strTableName.StartsWith("FA"))
                        if (strColumnName.Contains("FA" + Screen.Module.Name + "Type"))
                            if (ADConfigValueUtility.glbdsConfigValues.Tables[Screen.Module.Name + "Type"] != null)
                                if (e.CellValue != null)
                                {
                                    String strValue = e.CellValue.ToString();
                                    DataRow row = ADConfigValueUtility.glbdsConfigValues.Tables[Screen.Module.Name + "Type"].Rows.Find(strValue);
                                    if (row != null)
                                        e.DisplayText = row["Text"].ToString();
                                }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    (sender as DevExpress.XtraGrid.Views.Grid.GridView).Columns.Remove(e.Column);
                }
            }
        }

        private void GridControlSearchResults_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DevExpress.XtraGrid.GridControl dgcSearchResults = (DevExpress.XtraGrid.GridControl)sender;
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hi = ((DevExpress.XtraGrid.Views.Grid.GridView)dgcSearchResults.MainView).CalcHitInfo(new Point(e.X, e.Y));
            if (hi.RowHandle >= 0)
            {
                THSScreen _guiDataMainScreen = ((BaseModuleERP)Screen.Module).GetDataMainScreen(null, String.Empty);
                if (_guiDataMainScreen != null)
                {
                    _guiDataMainScreen.Activate();
                    Screen.Module.ActiveScreen = _guiDataMainScreen;
                }
            }
        }
        #endregion

        #region Add Search Results To GridControl Functions
        #region Utilities For Data GridControl View

        //public static void BindingSearchResultGridControl(DevExpress.XtraGrid.GridControl GridControlSearchResults, DataSet dsSearchResults, String strModuleName, String strTableName)
        //public static void AddSearchResultsToGridView(DevExpress.XtraGrid.GridControl GridControlSearchResults, String strModuleName, String strTableName)
        //public static void BindingSearchResultGridControl(DevExpress.XtraGrid.GridControl GridControlSearchResults, DataSet dsSearchResults)
        public static void BindingSearchResultGridControl(THSSearchResultsGridControl GridControlSearchResults, DataSet dsSearchResults)
        {
            if (dsSearchResults.Tables.Count > 0)
            {
                DevExpress.XtraGrid.Views.Grid.GridView gridView = (DevExpress.XtraGrid.Views.Grid.GridView)GridControlSearchResults.ViewCollection[0];
                gridView.OptionsBehavior.AutoPopulateColumns = false;

                BindingSource bdsSearchResults = new BindingSource();
                bdsSearchResults.DataSource = dsSearchResults.Tables[0];
                //hieu.nguyen add 05/7/2011

                if (!String.IsNullOrEmpty(GridControlSearchResults.THSSelectType))
                {
                    for (int i = 0; i < dsSearchResults.Tables[0].Rows.Count; i++)
                    {
                        DataRow row = dsSearchResults.Tables[0].Rows[i];
                        if (!row[GridControlSearchResults.THSSelectType].ToString().Contains(GridControlSearchResults.THSSelectTypeValue))
                        {
                            dsSearchResults.Tables[0].Rows.Remove(row);
                            i--;
                        }
                    }
                }
                GridControlSearchResults.DataSource = bdsSearchResults;             
            }
        }

        private static void InitDefaultGridViewResult(DevExpress.XtraGrid.Views.Grid.GridView GridViewResults, String strTableName)
        {
            // gold wichtig
            GridViewResults.OptionsView.ColumnAutoWidth = false;
            String strModuleName = strTableName.Substring(2, strTableName.Length - 3);

            String strPrimaryColumn = THSDbUtil.GetTablePrimaryColumn(strTableName);

            if (GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No"] != null)
            {
                GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No"].Width = 150;
                GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "No"].VisibleIndex = 1;
            }
            
            if (GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Name"] != null)
            {
                GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Name"].Width = 150;
                GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Name"].VisibleIndex = 2;
            }
            if (GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Desc"] != null)
            {
                GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Desc"].Width = 300;
                GridViewResults.Columns[strPrimaryColumn.Substring(0, strPrimaryColumn.Length - 2) + "Desc"].VisibleIndex = 3;
            }           
        }

        private void InitGridViewResult(DevExpress.XtraGrid.Views.Grid.GridView GridViewResults, String strModuleName, String strTableName)
        {
            
            //AddColumnsToGridViewResults(GridViewResults, strTableName);            
            STGridResultColumnDisplaysController objGridResultColumnDisplayController = new STGridResultColumnDisplaysController();
            
            DataSet dsColumns = objGridResultColumnDisplayController.GetGridResultColumnDisplaysByModuleName(strModuleName);
            if(dsColumns.Tables[0].Rows.Count>0)
            {
                foreach (DataRow rowColumn in dsColumns.Tables[0].Rows)
                {
                    STGridResultColumnDisplaysInfo objGridResultColumnDisplayInfo = (STGridResultColumnDisplaysInfo)objGridResultColumnDisplayController.GetObjectFromDataRow(rowColumn);
                    if (GridViewResults.Columns[objGridResultColumnDisplayInfo.STGridResultColumnFieldName] != null)
                    {
                        //GridViewResults.Columns[objGridResultColumnDisplayInfo.STGridResultColumnFieldName].Caption = objGridResultColumnDisplayInfo.STGridResultColumnCaption;
                        GridViewResults.Columns[objGridResultColumnDisplayInfo.STGridResultColumnFieldName].Caption = objGridResultColumnDisplayInfo.STGridResultColumnCaption;
                        GridViewResults.Columns[objGridResultColumnDisplayInfo.STGridResultColumnFieldName].VisibleIndex = objGridResultColumnDisplayInfo.STGridResultSortOrder;
                        GridViewResults.Columns[objGridResultColumnDisplayInfo.STGridResultColumnFieldName].Width = objGridResultColumnDisplayInfo.STGridResultColumnWidth;
                    }
                    else
                    {
                        DevExpress.XtraGrid.Columns.GridColumn col = new DevExpress.XtraGrid.Columns.GridColumn();
                        col.Name = "col" + objGridResultColumnDisplayInfo.STGridResultColumnFieldName;
                        col.FieldName = objGridResultColumnDisplayInfo.STGridResultColumnFieldName;
                        col.Caption = objGridResultColumnDisplayInfo.STGridResultColumnCaption;
                        col.Width = objGridResultColumnDisplayInfo.STGridResultColumnWidth;
                        col.VisibleIndex = objGridResultColumnDisplayInfo.STGridResultSortOrder;
                        GridViewResults.Columns.Add(col);
                    }
                }
            }            
            else
                InitDefaultGridViewResult(GridViewResults, strTableName);            
        }
        #endregion
        #endregion

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        
        private void NavigatorButton_Click(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            if (e.Button.Hint == "Customize")
                CustomizeColumnGridSearchResults();
            else
                if (e.Button.Hint == "Save Customization")
                    SaveCustomizeColumnGridSearchResults();
        }

        /// <summary type="Customize">
        /// Customize Column on Search Results Control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="SearchResultsControlName" type="String"></THSparam>
        private void CustomizeColumnGridSearchResults()
        {
            ((DevExpress.XtraGrid.Views.Grid.GridView)this.MainView).ColumnsCustomization();
        }

        /// <summary type="Save">
        /// Save customize column of Search Results Control
        /// </summary>
        /// <THSparam name="SearchResultsControlName" type="String"></THSparam>
        private void SaveCustomizeColumnGridSearchResults()
        {
            STGridResultColumnDisplaysController objSTGridResultColumnDisplaysController = new STGridResultColumnDisplaysController();
            objSTGridResultColumnDisplaysController.DeleteGridResultColumnDisplayByModuleName(Screen.Module.Name);

            foreach (DevExpress.XtraGrid.Columns.GridColumn gridColumn in ((DevExpress.XtraGrid.Views.Grid.GridView)this.MainView).Columns)
            {
                if (gridColumn.Visible)
                {
                    STGridResultColumnDisplaysInfo objSTGridResultColumnDisplaysInfo = new STGridResultColumnDisplaysInfo();
                    objSTGridResultColumnDisplaysInfo.STGridResultColumnName = gridColumn.Name;
                    objSTGridResultColumnDisplaysInfo.STGridResultColumnFieldName = gridColumn.FieldName;
                    objSTGridResultColumnDisplaysInfo.STGridResultColumnCaption = gridColumn.Caption;
                    objSTGridResultColumnDisplaysInfo.STGridResultColumnWidth = gridColumn.Width;
                    objSTGridResultColumnDisplaysInfo.STModuleID = new STModulesController().GetObjectIDByName(Screen.Module.Name);
                    objSTGridResultColumnDisplaysInfo.STGridResultSortOrder = gridColumn.VisibleIndex;
                    objSTGridResultColumnDisplaysController.CreateObject(objSTGridResultColumnDisplaysInfo);
                }
            }
            MessageBox.Show("Save successfully.", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
